﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.IO;
using System.Windows.Controls;
using System.Windows.Data;
using System.Xml.Linq;
using System.Windows.Forms;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Runtime.InteropServices;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.Collections;
using System.Speech.Synthesis;
using System.Drawing.Printing;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Media;
using DiasEngineDate.UI;

namespace DiasEngineDate
{
    public class FunctionINC
    {

        //引用配置文件库
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);

        #region 角色管理模块

        //绑定combox系统级别
        public void BindingLevel(System.Windows.Controls.ComboBox _level)
        {
            // 绑定下拉菜单
            //加载数据、读取数据库数据到下拉菜单、comboBox中、
            //链接数据库
            Conning conn = new Conning();
            string sql = "select * from Dias_SystemLevel";
            SqlCommand cmd = new SqlCommand(sql, conn.sqlconn);
            SqlDataAdapter sda = new SqlDataAdapter(sql, conn.sqlconn);
            DataSet ds = new DataSet();
            sda.Fill(ds, "Dias_SystemLevel");
            _level.ItemsSource = ds.Tables["Dias_SystemLevel"].DefaultView;
            _level.DisplayMemberPath = ds.Tables["Dias_SystemLevel"].Columns["Sys_Level"].ToString();
            _level.SelectedValuePath = ds.Tables["Dias_SystemLevel"].Columns["ID"].ToString();
            _level.SelectedIndex = 0;//默认显示第一项
            conn.sqlconn.Close();
        }

        //上传系统管理员头像
        public void SettingSuserPhoto(Ellipse _rand, System.Windows.Controls.TextBox txtbox)
        {
            //创建一个文本对象保存路径
            string imgpath = "";
            //创建一个对话框对象
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.InitialDirectory = System.AppDomain.CurrentDomain.BaseDirectory + @"SysUserImg\";//指定打开的路劲
            //为对话框设置标题
            ofd.Title = "请选择上传的图片";
            //设置筛选的图片格式
            ofd.Filter = "图片(jpg/jpeg/png/bmp/gif)|*.jpg;*.jpeg;*.png;*.bmp;*.gif";
            //设置是否允许多选
            ofd.Multiselect = false;
            //如果你点了“确定”按钮
            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                //获得文件的完整路径（包括名字后后缀）
                string filePath = ofd.FileName;
                //将文件路径显示在文本框中
                //txtImgUrl.Text = filePath;
                //找到文件名比如“1.jpg”前面的那个“\”的位置
                int position = filePath.LastIndexOf("\\");
                //从完整路径中截取出来文件名“1.jpg”
                string fileName = filePath.Substring(position + 1);
                //读取选择的文件，返回一个流
                using (Stream stream = ofd.OpenFile())
                {
                    //创建一个流，用来写入得到的文件流（注意：创建一个名为“Images”的文件夹，如果是用相对路径，必须在这个程序的Degug目录下创建
                    //如果是绝对路径，放在那里都行，我用的是相对路径）

                    //检测路径是否存在。如
                    String strPath = System.AppDomain.CurrentDomain.BaseDirectory + @"SysUserImg\";
                    if (Directory.Exists(strPath))
                    {
                        //存在就尝试写入图片
                        if (File.Exists(System.AppDomain.CurrentDomain.BaseDirectory + @"SysUserImg\" + fileName))
                        {

                        }
                        else
                        {
                            try
                            {
                                using (FileStream fs = new FileStream(System.AppDomain.CurrentDomain.BaseDirectory + @"SysUserImg\" + fileName, FileMode.CreateNew))
                                {

                                    //将得到的文件流复制到写入流中
                                    stream.CopyTo(fs);
                                    //将写入流中的数据写入到文件中
                                    fs.Flush();
                                }

                            }
                            catch (Exception)
                            {

                            }
                        }
                    }
                    else
                    {
                        //不存在就建立文件夹并且写入图片
                        Directory.CreateDirectory(System.AppDomain.CurrentDomain.BaseDirectory + @"SysUserImg\");//简历文件夹
                        //存在就尝试写入图片
                        if (File.Exists(System.AppDomain.CurrentDomain.BaseDirectory + @"SysUserImg\" + fileName))
                        {

                        }
                        else
                        {
                            try
                            {
                                using (FileStream fs = new FileStream(System.AppDomain.CurrentDomain.BaseDirectory + @"SysUserImg\" + fileName, FileMode.CreateNew))
                                {

                                    //将得到的文件流复制到写入流中
                                    stream.CopyTo(fs);
                                    //将写入流中的数据写入到文件中
                                    fs.Flush();
                                }

                            }
                            catch (Exception)
                            {

                            }
                        }
                    }

                    //设置用户头像
                    ImageBrush imgBrush = new ImageBrush();
                    imgBrush.ImageSource = new BitmapImage(new Uri(System.AppDomain.CurrentDomain.BaseDirectory + @"SysUserImg\" + fileName, UriKind.Absolute));
                    _rand.Fill = imgBrush;

                    //将图像保存到数据库记录保存到配置文件
                    //返回一个路径。然后好保存到数据库
                    imgpath = new Uri(System.AppDomain.CurrentDomain.BaseDirectory + @"SysUserImg\" + fileName, UriKind.Absolute).ToString();
                    int end = imgpath.LastIndexOf("/");
                    txtbox.Text = (imgpath.Substring(end)).Remove(0,1);
                }
            }
        }

        //上传车型品牌图片
        public void UploadCarImg(Ellipse _rand, System.Windows.Controls.TextBox txtbox)
        {
            //创建一个文本对象保存路径
            string imgpath = "";
            //创建一个对话框对象
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.InitialDirectory = System.AppDomain.CurrentDomain.BaseDirectory + @"CarImg\";//指定打开的路劲
            //为对话框设置标题
            ofd.Title = "请选择上传的图片";
            //设置筛选的图片格式
            ofd.Filter = "图片(jpg/jpeg/png/bmp/gif)|*.jpg;*.jpeg;*.png;*.bmp;*.gif";
            //设置是否允许多选
            ofd.Multiselect = false;
            //如果你点了“确定”按钮
            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                //获得文件的完整路径（包括名字后后缀）
                string filePath = ofd.FileName;
                //将文件路径显示在文本框中
                //txtImgUrl.Text = filePath;
                //找到文件名比如“1.jpg”前面的那个“\”的位置
                int position = filePath.LastIndexOf("\\");
                //从完整路径中截取出来文件名“1.jpg”
                string fileName = filePath.Substring(position + 1);
                //读取选择的文件，返回一个流
                using (Stream stream = ofd.OpenFile())
                {
                    //创建一个流，用来写入得到的文件流（注意：创建一个名为“Images”的文件夹，如果是用相对路径，必须在这个程序的Degug目录下创建
                    //如果是绝对路径，放在那里都行，我用的是相对路径）

                    //检测路径是否存在。如
                    String strPath = System.AppDomain.CurrentDomain.BaseDirectory + @"CarImg\";
                    if (Directory.Exists(strPath))
                    {
                        //存在就尝试写入图片
                        if (File.Exists(System.AppDomain.CurrentDomain.BaseDirectory + @"CarImg\" + fileName))
                        {

                        }
                        else
                        {
                            try
                            {
                                using (FileStream fs = new FileStream(System.AppDomain.CurrentDomain.BaseDirectory + @"CarImg\" + fileName, FileMode.CreateNew))
                                {

                                    //将得到的文件流复制到写入流中
                                    stream.CopyTo(fs);
                                    //将写入流中的数据写入到文件中
                                    fs.Flush();
                                }

                            }
                            catch (Exception)
                            {

                            }
                        }
                    }
                    else
                    {
                        //不存在就建立文件夹并且写入图片
                        Directory.CreateDirectory(System.AppDomain.CurrentDomain.BaseDirectory + @"CarImg\");//简历文件夹
                        //存在就尝试写入图片
                        if (File.Exists(System.AppDomain.CurrentDomain.BaseDirectory + @"CarImg\" + fileName))
                        {

                        }
                        else
                        {
                            try
                            {
                                using (FileStream fs = new FileStream(System.AppDomain.CurrentDomain.BaseDirectory + @"CarImg\" + fileName, FileMode.CreateNew))
                                {

                                    //将得到的文件流复制到写入流中
                                    stream.CopyTo(fs);
                                    //将写入流中的数据写入到文件中
                                    fs.Flush();
                                }

                            }
                            catch (Exception)
                            {

                            }
                        }
                    }

                    //设置用户头像
                    ImageBrush imgBrush = new ImageBrush();
                    imgBrush.ImageSource = new BitmapImage(new Uri(System.AppDomain.CurrentDomain.BaseDirectory + @"CarImg\" + fileName, UriKind.Absolute));
                    _rand.Fill = imgBrush;

                    //将图像保存到数据库记录保存到配置文件
                    //返回一个路径。然后好保存到数据库
                    imgpath = new Uri(System.AppDomain.CurrentDomain.BaseDirectory + @"CarImg\" + fileName, UriKind.Absolute).ToString();
                    int end = imgpath.LastIndexOf("/");
                    txtbox.Text = (imgpath.Substring(end)).Remove(0, 1);
                }
            }
        }

        //上传钥匙图片
        public void UpdateGoodsImg(System.Windows.Controls.TextBox txtbox)
        {
            //创建一个文本对象保存路径
            string imgpath = "";
            //创建一个对话框对象
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.InitialDirectory = System.AppDomain.CurrentDomain.BaseDirectory + @"KeysImg\";//指定打开的路劲
            //为对话框设置标题
            ofd.Title = "请选择上传的图片";
            //设置筛选的图片格式
            ofd.Filter = "图片(jpg/jpeg/png/bmp/gif)|*.jpg;*.jpeg;*.png;*.bmp;*.gif";
            //设置是否允许多选
            ofd.Multiselect = false;
            //如果你点了“确定”按钮
            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                //获得文件的完整路径（包括名字后后缀）
                string filePath = ofd.FileName;
                //将文件路径显示在文本框中
                //txtImgUrl.Text = filePath;
                //找到文件名比如“1.jpg”前面的那个“\”的位置
                int position = filePath.LastIndexOf("\\");
                //从完整路径中截取出来文件名“1.jpg”
                string fileName = filePath.Substring(position + 1);
                //读取选择的文件，返回一个流
                using (Stream stream = ofd.OpenFile())
                {
                    //创建一个流，用来写入得到的文件流（注意：创建一个名为“Images”的文件夹，如果是用相对路径，必须在这个程序的Degug目录下创建
                    //如果是绝对路径，放在那里都行，我用的是相对路径）

                    //检测路径是否存在。如
                    String strPath = System.AppDomain.CurrentDomain.BaseDirectory + @"KeysImg\";
                    if (Directory.Exists(strPath))
                    {
                        //存在就尝试写入图片
                        if (File.Exists(System.AppDomain.CurrentDomain.BaseDirectory + @"KeysImg\" + fileName))
                        {

                        }
                        else
                        {
                            try
                            {
                                using (FileStream fs = new FileStream(System.AppDomain.CurrentDomain.BaseDirectory + @"KeysImg\" + fileName, FileMode.CreateNew))
                                {

                                    //将得到的文件流复制到写入流中
                                    stream.CopyTo(fs);
                                    //将写入流中的数据写入到文件中
                                    fs.Flush();
                                }

                            }
                            catch (Exception)
                            {

                            }
                        }
                    }
                    else
                    {
                        //不存在就建立文件夹并且写入图片
                        Directory.CreateDirectory(System.AppDomain.CurrentDomain.BaseDirectory + @"KeysImg\");//简历文件夹
                        //存在就尝试写入图片
                        if (File.Exists(System.AppDomain.CurrentDomain.BaseDirectory + @"KeysImg\" + fileName))
                        {

                        }
                        else
                        {
                            try
                            {
                                using (FileStream fs = new FileStream(System.AppDomain.CurrentDomain.BaseDirectory + @"KeysImg\" + fileName, FileMode.CreateNew))
                                {

                                    //将得到的文件流复制到写入流中
                                    stream.CopyTo(fs);
                                    //将写入流中的数据写入到文件中
                                    fs.Flush();
                                }

                            }
                            catch (Exception)
                            {

                            }
                        }
                    }

                    //设置用户头像
                    //ImageBrush imgBrush = new ImageBrush();
                    //imgBrush.ImageSource = new BitmapImage(new Uri(System.AppDomain.CurrentDomain.BaseDirectory + @"KeysImg\" + fileName, UriKind.Absolute));
                    //_rand.Fill = imgBrush;

                    //将图像保存到数据库记录保存到配置文件
                    //返回一个路径。然后好保存到数据库
                    imgpath = new Uri(System.AppDomain.CurrentDomain.BaseDirectory + @"KeysImg\" + fileName, UriKind.Absolute).ToString();
                    int end = imgpath.LastIndexOf("/");
                    txtbox.Text = (imgpath.Substring(end)).Remove(0, 1);
                }
            }
        }

        //将添加内容写进数据库
        public void AddSysUserInformation(string _cname,string _ename,string _syspassword,string _userphoto,DateTime _addtime,System.Windows.Controls.DataGrid _dg)
        {
            Conning conn = new Conning();
            //判断该部门下面是否存在该分组数据
            string sql = "select count(*) from Dias_SystemUser where EName=@ename";
            SqlCommand xtcmd = new SqlCommand(sql, conn.sqlconn);
            xtcmd.Parameters.AddWithValue("@ename", _ename);
            int count = (int)xtcmd.ExecuteScalar();
            if (count > 0)
            {
                MessageBox.Show("操作失败", "数据库中已经存在相同用户？请核实后再进行添加？");
                return;
            }
            //执行添加员工操作
            string usql = string.Format("insert into Dias_SystemUser(CName,EName,UserPassword,UserPhoto,UserTime) values('{0}','{1}','{2}','{3}','{4}')", _cname, _ename, Encryption_Decryption.Encrypt(_syspassword), _userphoto, _addtime);
            SqlCommand ucmd = new SqlCommand(usql, conn.sqlconn);
            ucmd.ExecuteNonQuery();

            MessageBox.Show("操作成功", "数据库引擎启动成功？数据插入完成？");

            //添加成功、将记录存入操作记录中
            //Dias_SystemUser_action(Login.Suser, _uname, "员工入职");
            //uconn.sqlconn.Close();

            //重新刷新数据绑定
            BingdingSysUserDataGrid(_dg);

            //释放内存垃圾
            conn.sqlconn.Close();
        }

        //将用户绑定到表格
        public void BingdingSysUserDataGrid(System.Windows.Controls.DataGrid _dg)
        {
            Conning conn = new Conning();
            //执行数据查询、将数据绑定到datagridview
            string sql = "select * from Dias_SystemUser order by ID desc";
            SqlDataAdapter sda = new SqlDataAdapter(sql, conn.sqlconn);
            DataSet ds = new DataSet();
            sda.Fill(ds, "Dias_SystemUser");
            //判断是否有数据
            SqlCommand cmd = new SqlCommand(sql, conn.sqlconn);
            SqlDataReader dr;
            dr = cmd.ExecuteReader();
            if (dr.Read())//有数据
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    ds.Tables[0].Rows[i][4] = new Uri(System.AppDomain.CurrentDomain.BaseDirectory + @"SysUserImg\" + ds.Tables[0].Rows[i][4], UriKind.Absolute).ToString();
                }

                //绑定数据
                _dg.ItemsSource = ds.Tables["Dias_SystemUser"].DefaultView;
            }
            else
            {
                _dg.ItemsSource = ds.Tables["Dias_SystemUser"].DefaultView;
            }

            conn.sqlconn.Close();
        }

        //更新用户角色
        public void UpdateSysUser(string _jieb,string _zhh,string _mm,string _img,int _id)
        {
            Conning edconn = new Conning();
            string poxtsql = "Update Dias_SystemUser set CName=@cname,EName=@ename,UserPassword=@mm,UserPhoto=@img,UserTime=@utime where ID=@id";
            SqlCommand updataordercmd = new SqlCommand(poxtsql, edconn.sqlconn);
            updataordercmd.Parameters.AddWithValue("@cname", _jieb);
            updataordercmd.Parameters.AddWithValue("@ename", _zhh);
            updataordercmd.Parameters.AddWithValue("@mm", _mm);
            updataordercmd.Parameters.AddWithValue("@img", _img);
            updataordercmd.Parameters.AddWithValue("@utime", DateTime.Now.ToString());
            updataordercmd.Parameters.AddWithValue("@id", _id);
            updataordercmd.ExecuteNonQuery();
            edconn.sqlconn.Close();
        }


        //删除用户角色
        public void DeleteSysUser(long _id,System.Windows.Controls.DataGrid _dg) 
        {
            string headimg;
            string bgimg;

            Conning conn = new Conning();
            SqlDataAdapter sda = new SqlDataAdapter("select * from Dias_SystemUser where ID="+_id, conn.sqlconn);
            DataTable dt = new DataTable();
            sda.Fill(dt);
            headimg = dt.Rows[0]["UserPhoto"].ToString();
            bgimg = dt.Rows[0]["UserBackground"].ToString();

            //
            //判断是否有一条数据，如果数据只有一条，不执行删除，
            SqlCommand filecmd = new SqlCommand("select count(*) from Dias_SystemUser", conn.sqlconn);
            int count = (int)filecmd.ExecuteScalar();
            if (count==1)//只有一条，不删除
            {
                MessageBox.Show("系统必须保留一个系统管理员？删除失败？");
            }
            else
            {
                //删除图片文件
                //判断文件是否存在
                if (bgimg!="")
                {
                    if (File.Exists(System.AppDomain.CurrentDomain.BaseDirectory + @"Videos\" + bgimg))
	                {
                         //获得目录下头像图片文件并删除
                        string pt = System.AppDomain.CurrentDomain.BaseDirectory + @"Videos\" + bgimg;
                        try
                        {
                            File.Delete(pt);
                        }
                        catch (Exception)
                        {
                            
                        }
		            
	                }
                    if (File.Exists(System.AppDomain.CurrentDomain.BaseDirectory + @"SysUserImg\" + headimg))
	                {
                        //获得目录下背景图像文件并删除
                        string bg = System.AppDomain.CurrentDomain.BaseDirectory + @"SysUserImg\" + headimg;
                        try
                        {
                            
                        }
                        catch (Exception)
                        {
                            
                        }
		            
	                }
                }
                
                //删除数据库数据
                string sql = "delete from Dias_SystemUser where ID=@id";
                SqlCommand cmd = new SqlCommand(sql, conn.sqlconn);
                cmd.Parameters.AddWithValue("@id", _id);
                cmd.ExecuteNonQuery();
            }
            conn.sqlconn.Close();

            //刷新数据库
            BingdingSysUserDataGrid(_dg);
        }

        //添加系统级别
        public void AddLeavel(string _lvalue)
        {
            Conning conn = new Conning();
            //判断该级别是否已经存在
            string sql = "select count(*) from Dias_SystemLevel where Sys_Level=@ename";
            SqlCommand xtcmd = new SqlCommand(sql, conn.sqlconn);
            xtcmd.Parameters.AddWithValue("@ename", _lvalue);
            int count = (int)xtcmd.ExecuteScalar();
            if (count > 0)
            {
                MessageBox.Show("操作失败", "数据库中已经存在该级别？请核实后再进行添加？");
                return;
            }
            //执行添加员工操作
            string usql = string.Format("insert into Dias_SystemLevel(Sys_Level,Sys_Time) values('{0}','{1}')", _lvalue,DateTime.Now.ToString());
            SqlCommand ucmd = new SqlCommand(usql, conn.sqlconn);
            ucmd.ExecuteNonQuery();

            MessageBox.Show("操作成功", "数据插入完成？");
        }
        #endregion

        #region 库存管理模块
        //绑定芯片型号信息
        public void BangdingChipModels(System.Windows.Controls.ComboBox _combox, int _id)
        {
            Conning conn = new Conning();
            //将获取到的部门ID转换为部门名称
            //获取ID读取数据库
            string sql = "select * from Dias_CarClass where ID=" + _id;
            SqlDataAdapter sda = new SqlDataAdapter(sql, conn.sqlconn);
            SqlCommandBuilder scb = new SqlCommandBuilder(sda);
            DataTable dt = new DataTable();
            sda.Fill(dt);
            //string[] pruduction_department = new string[dt.Rows.Count];
            string poname = dt.Rows[0]["Car_Name"].ToString();


            //添加员工，添加部门信息到下拉列表

            string gsqlstring = "select * from Dias_Chips where Car_Class='" + poname + "'";
            SqlCommand gcmd = new SqlCommand(gsqlstring, conn.sqlconn);
            SqlDataAdapter gsda = new SqlDataAdapter(gsqlstring, conn.sqlconn);
            DataSet gds = new DataSet();
            gsda.Fill(gds, "Dias_Chips");
            _combox.ItemsSource = gds.Tables["Dias_Chips"].DefaultView;
            _combox.DisplayMemberPath = gds.Tables["Dias_Chips"].Columns["Chip_Modles"].ToString();
            _combox.SelectedValuePath = gds.Tables["Dias_Chips"].Columns["ID"].ToString();
            _combox.SelectedIndex = 0;//默认显示第一项
            conn.sqlconn.Close();
        }

        //根据芯片型号绑定其他芯片信息
        public void BangdingChipModelsOhter(System.Windows.Controls.ComboBox _combox,System.Windows.Controls.ComboBox combox1,System.Windows.Controls.ComboBox combox2, int _id)
        {
            Conning conn = new Conning();
            //将获取到的部门ID转换为部门名称
            //获取ID读取数据库
            string sql = "select * from Dias_Chips where ID=" + _id;
            SqlDataAdapter sda = new SqlDataAdapter(sql, conn.sqlconn);
            SqlCommandBuilder scb = new SqlCommandBuilder(sda);
            DataTable dt = new DataTable();
            sda.Fill(dt);
            //string[] pruduction_department = new string[dt.Rows.Count];
            string poname = dt.Rows[0]["Chip_Modles"].ToString();


            //添加员工，添加部门信息到下拉列表

            string gsqlstring = "select * from Dias_Chips where Chip_Modles='" + poname + "'";
            SqlCommand gcmd = new SqlCommand(gsqlstring, conn.sqlconn);
            SqlDataAdapter gsda = new SqlDataAdapter(gsqlstring, conn.sqlconn);
            DataSet gds = new DataSet();
            gsda.Fill(gds, "Dias_Chips");
            
            //适用车型
            _combox.ItemsSource = gds.Tables["Dias_Chips"].DefaultView;
            _combox.DisplayMemberPath = gds.Tables["Dias_Chips"].Columns["Chip_Size"].ToString();
            _combox.SelectedValuePath = gds.Tables["Dias_Chips"].Columns["ID"].ToString();
            _combox.SelectedIndex = 0;//默认显示第一项

            //编号
            combox1.ItemsSource = gds.Tables["Dias_Chips"].DefaultView;
            combox1.DisplayMemberPath = gds.Tables["Dias_Chips"].Columns["Chip_ID"].ToString();
            combox1.SelectedValuePath = gds.Tables["Dias_Chips"].Columns["ID"].ToString();
            combox1.SelectedIndex = 0;//默认显示第一项

            //价格
            combox2.ItemsSource = gds.Tables["Dias_Chips"].DefaultView;
            combox2.DisplayMemberPath = gds.Tables["Dias_Chips"].Columns["Chip_Price"].ToString();
            combox2.SelectedValuePath = gds.Tables["Dias_Chips"].Columns["ID"].ToString();
            combox2.SelectedIndex = 0;//默认显示第一项
            conn.sqlconn.Close();
        }

        //更新库存信息
        public void UpdateInvertory(string _chipname, int _chipnum)
        {
            Conning edconn = new Conning();

            //取得之前的存库量
            string sqlbd = "select * from Dias_Keys_Informations where Chip_Models='" + _chipname + "' order by ID ASC";
            SqlDataAdapter sdabd = new SqlDataAdapter(sqlbd, edconn.sqlconn);
            DataSet dsbd = new DataSet();
            sdabd.Fill(dsbd, "Dias_Keys_Informations");
            _chipnum = Convert.ToInt32(_chipnum) + Convert.ToInt32(dsbd.Tables[0].Rows[0][7]);

            //更新
            string poxtsql = "Update Dias_Keys_Informations set The_Num=@chipnum,Action_Time=@utime where Chip_Models=@chipmodels";
            SqlCommand updataordercmd = new SqlCommand(poxtsql, edconn.sqlconn);
            updataordercmd.Parameters.AddWithValue("@chipnum", _chipnum);
            updataordercmd.Parameters.AddWithValue("@chipmodels", _chipname);
            updataordercmd.Parameters.AddWithValue("@utime", DateTime.Now.ToString());

            updataordercmd.ExecuteNonQuery();
            edconn.sqlconn.Close();
        }

        //出库操作
        public void OutUpdateInvertory(int _id, int _chipnum)
        {
            Conning edconn = new Conning();

            //取得之前的存库量
            string sqlbd = "select * from Dias_Keys_Informations where ID=" +_id + " order by ID ASC";
            SqlDataAdapter sdabd = new SqlDataAdapter(sqlbd, edconn.sqlconn);
            DataSet dsbd = new DataSet();
            sdabd.Fill(dsbd, "Dias_Keys_Informations");
            _chipnum = Convert.ToInt32(dsbd.Tables[0].Rows[0][6])-_chipnum;

            //更新
            string poxtsql = "Update Dias_Keys_Informations set The_Num=@chipnum,Action_Time=@utime where ID=@id";
            SqlCommand updataordercmd = new SqlCommand(poxtsql, edconn.sqlconn);
            updataordercmd.Parameters.AddWithValue("@chipnum", _chipnum);
            updataordercmd.Parameters.AddWithValue("@id", _id);
            updataordercmd.Parameters.AddWithValue("@utime", DateTime.Now.ToString());

            updataordercmd.ExecuteNonQuery();
            edconn.sqlconn.Close();
        }

        //查询车牌存在的钥匙或者芯片
        public void BangdingKC(System.Windows.Controls.DataGrid _dategrid, int _id)
        {
            Conning conn = new Conning();
            //将获取到的部门ID转换为部门名称
            //获取ID读取数据库
            string sql = "select * from Dias_CarClass where ID=" + _id;
            SqlDataAdapter sda = new SqlDataAdapter(sql, conn.sqlconn);
            SqlCommandBuilder scb = new SqlCommandBuilder(sda);
            DataTable dt = new DataTable();
            sda.Fill(dt);
            //string[] pruduction_department = new string[dt.Rows.Count];
            string poname = dt.Rows[0]["Car_Name"].ToString();


            //添加员工，添加部门信息到下拉列表

            //重新绑定dategrid
            string sqlbd = "select * from Dias_Keys_Informations where Car_Class='"+poname+"' order by ID ASC";
            SqlDataAdapter sdabd = new SqlDataAdapter(sqlbd, conn.sqlconn);
            DataSet dsbd = new DataSet();
            sdabd.Fill(dsbd, "Dias_Keys_Informations");
            //判断是否有数据
            SqlCommand cmdbd = new SqlCommand(sqlbd, conn.sqlconn);
            SqlDataReader dr;
            dr = cmdbd.ExecuteReader();
            if (dr.Read())//有数据
            {
                //for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                //{
                //    ds.Tables[0].Rows[i][4] = new Uri(System.AppDomain.CurrentDomain.BaseDirectory + @"SysUserImg\" + ds.Tables[0].Rows[i][4], UriKind.Absolute).ToString();
                //}

                //绑定数据
                _dategrid.ItemsSource = dsbd.Tables["Dias_Keys_Informations"].DefaultView;
            }
            else
            {
                _dategrid.ItemsSource = dsbd.Tables["Dias_Keys_Informations"].DefaultView;
            }
            conn.sqlconn.Close();
        }


        #endregion

        #region 背景设置
        //上传视频
        public void SettingVideo(MediaElement _video, string _user)
        {
            //创建一个对话框对象
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.InitialDirectory = System.AppDomain.CurrentDomain.BaseDirectory + @"Videos\";//指定打开的路劲
            //为对话框设置标题
            ofd.Title = "请选择上传的图片";
            //设置筛选的图片格式
            ofd.Filter = "图片(jpg/jpeg/png/bmp/gif)|*.jpg;*.jpeg;*.png;*.bmp;*.gif|视频(mp4/3gp/wmv/avi)|*.mp4;*.3gp;*.wmv;*.avi";
            //设置是否允许多选
            ofd.Multiselect = false;
            //如果你点了“确定”按钮
            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                //获得文件的完整路径（包括名字后后缀）
                string filePath = ofd.FileName;
                //将文件路径显示在文本框中
                //txtImgUrl.Text = filePath;
                //找到文件名比如“1.jpg”前面的那个“\”的位置
                int position = filePath.LastIndexOf("\\");
                //从完整路径中截取出来文件名“1.jpg”
                string fileName = filePath.Substring(position + 1);
                //读取选择的文件，返回一个流
                using (Stream stream = ofd.OpenFile())
                {
                    //创建一个流，用来写入得到的文件流（注意：创建一个名为“Images”的文件夹，如果是用相对路径，必须在这个程序的Degug目录下创建
                    //如果是绝对路径，放在那里都行，我用的是相对路径）

                    //检测路径是否存在。如
                    String strPath = System.AppDomain.CurrentDomain.BaseDirectory + @"\Videos\";
                    if (Directory.Exists(strPath))
                    {
                        //存在就尝试写入图片
                        if (File.Exists(System.AppDomain.CurrentDomain.BaseDirectory + @"\Videos\" + fileName))
                        {

                        }
                        else
                        {
                            try
                            {
                                using (FileStream fs = new FileStream(System.AppDomain.CurrentDomain.BaseDirectory + @"\Videos\" + fileName, FileMode.CreateNew))
                                {

                                    //将得到的文件流复制到写入流中
                                    stream.CopyTo(fs);
                                    //将写入流中的数据写入到文件中
                                    fs.Flush();
                                }

                            }
                            catch (Exception)
                            {

                            }
                        }
                    }
                    else
                    {
                        //不存在就建立文件夹并且写入图片
                        Directory.CreateDirectory(System.AppDomain.CurrentDomain.BaseDirectory + @"\Videos\");//简历文件夹
                        //存在就尝试写入图片
                        if (File.Exists(System.AppDomain.CurrentDomain.BaseDirectory + @"\Videos\" + fileName))
                        {

                        }
                        else
                        {
                            try
                            {
                                using (FileStream fs = new FileStream(System.AppDomain.CurrentDomain.BaseDirectory + @"\Videos\" + fileName, FileMode.CreateNew))
                                {

                                    //将得到的文件流复制到写入流中
                                    stream.CopyTo(fs);
                                    //将写入流中的数据写入到文件中
                                    fs.Flush();
                                }

                            }
                            catch (Exception)
                            {

                            }
                        }
                    }
                    _video.Source = new Uri(System.AppDomain.CurrentDomain.BaseDirectory + @"Videos\" + fileName, UriKind.Absolute);
                    _video.Position = TimeSpan.FromSeconds(0);
                    _video.Play();

                    //将修改背景记录保存到数据库
                    Conning conn = new Conning();
                    string sql = "update Dias_SystemUser SET UserBackground = '" + fileName + "' WHERE EName = '" + _user + "'";
                    SqlCommand cmd = new SqlCommand(sql, conn.sqlconn);
                    cmd.ExecuteNonQuery();
                    //添加成功、将记录存入操作记录中

                    //释放内存垃圾
                    conn.sqlconn.Close();
                }
            }
        }

        //设置用户上次设置的背景视频
        public void SettingVideosbg(MediaElement _video, string _user)
        {
            //string user = Encryption_Decryption.Decrypt(IniReadValue("User", "username", AppDomain.CurrentDomain.BaseDirectory + "\\Config.ini"));//读取上次登录用户名并且解密
            //string filename = Encryption_Decryption.Decrypt(IniReadValue("VideoURL", "videourl", AppDomain.CurrentDomain.BaseDirectory + "\\Config.ini"));//读取保存的图片文件路径并且解密
            //if (user == "" || user != _user)
            //{
                //_video.Source = new Uri(System.AppDomain.CurrentDomain.BaseDirectory + @"\Videos\MainBG.jpg", UriKind.Absolute);
                //_video.Position = TimeSpan.FromSeconds(0);
                //_video.Play();
            //}
            //else//读取到用户名就设置视频
            //{
                //if (Directory.Exists(System.AppDomain.CurrentDomain.BaseDirectory + @"\Videos\"))
                //{
                    //if (File.Exists(filename))
                    //{
                        //_video.Source = new Uri(filename, UriKind.Absolute);
                        //_video.Position = TimeSpan.FromSeconds(0);
                        //_video.Play();
                    //}
                    //else
                    //{
                        //_video.Source = new Uri(System.AppDomain.CurrentDomain.BaseDirectory + @"\Videos\MainBG.jpg", UriKind.Absolute);
                       // _video.Position = TimeSpan.FromSeconds(0);
                        //_video.Play();

                    //}
                //}
            //
        }

        //慢慢影藏
        public void Slidingstart(MediaElement _video)
        {
            DoubleAnimation startsetting = new DoubleAnimation();
            startsetting.To = 0;
            startsetting.From = 1;
            startsetting.Duration = TimeSpan.FromSeconds(5);
            _video.BeginAnimation(MediaElement.OpacityProperty, startsetting);
        }

        //慢慢显示
        public void Slidingend(MediaElement _video)
        {
            DoubleAnimation endsetting = new DoubleAnimation();
            endsetting.To = 1;
            endsetting.From = 0;
            endsetting.Duration = TimeSpan.FromSeconds(5);
            _video.BeginAnimation(MediaElement.OpacityProperty, endsetting);
        }

        //读取INI文件方法
        static public string IniReadValue(string Section, string Key, string filepath)
        {
            StringBuilder temp = new StringBuilder(255);
            int i = GetPrivateProfileString(Section, Key, "", temp, 255, filepath);
            return temp.ToString();
        }

        //判断是否是图片
        public bool isImg(string FileName)
        {
            string[] extendFileName = { ".jpg", ".gif", ".bmp", ".png", ".BMP", ".JPG", ".GIF", ".PNG" };

            string[] arr = FileName.Split('.');
            if (arr.Length == 0)
                return false;
            string cjm = "." + arr[arr.Length - 1];
            bool isimg = false;
            if (arr.Length == 2)
                for (int j = 0; j < extendFileName.Length && !isimg; j++)
                {
                    if (cjm == extendFileName[j])
                        isimg = true;
                }
            return isimg;
        }
        #endregion

        #region 全局设置保存数据库
        
        //登录成功设置登录用户头像
        public void SettingLoginUserPhoto(string _user, Ellipse _ellipseWithImageBrush)
        {
            Conning conn = new Conning();
            string sqlinusername = "select UserPhoto from Dias_SystemUser where EName=@user";
            SqlCommand luncmd = new SqlCommand(sqlinusername, conn.sqlconn);
            luncmd.Parameters.AddWithValue("@user", _user);
            string Ppath = (string)luncmd.ExecuteScalar();

            if (File.Exists(System.AppDomain.CurrentDomain.BaseDirectory + @"SysUserImg\"+Ppath))
            {
                ImageBrush imgBrush = new ImageBrush();
                imgBrush.ImageSource = new BitmapImage(new Uri(System.AppDomain.CurrentDomain.BaseDirectory + @"SysUserImg\" + Ppath, UriKind.Absolute));
                _ellipseWithImageBrush.Fill = imgBrush;
            }
            else
            {
                ImageBrush imgBrush = new ImageBrush();
                imgBrush.ImageSource = new BitmapImage(new Uri(System.AppDomain.CurrentDomain.BaseDirectory + @"SysUserImg\User.png", UriKind.Absolute));
                _ellipseWithImageBrush.Fill = imgBrush;
            }
            
        }

        //登录成功设置登录用户背景
        public void SettingLoginUserBackground(string _user, MediaElement _video)
        {
            try
            {
            Conning conn = new Conning();
            string sqlinusername = "select UserBackground from Dias_SystemUser where EName=@user";
            SqlCommand luncmd = new SqlCommand(sqlinusername, conn.sqlconn);
            luncmd.Parameters.AddWithValue("@user", _user);
            string BGpath = (string)luncmd.ExecuteScalar();
            if (BGpath!="")
            {
                if (File.Exists(System.AppDomain.CurrentDomain.BaseDirectory + @"Videos\" + BGpath))
                {
                    _video.Source = new Uri(System.AppDomain.CurrentDomain.BaseDirectory + @"Videos\" + BGpath, UriKind.Absolute);
                    _video.Position = TimeSpan.FromSeconds(0);
                    _video.Play();
                }
                else
                {
                    _video.Source = new Uri(System.AppDomain.CurrentDomain.BaseDirectory + @"Videos\Mainbg.avi", UriKind.Absolute);
                    _video.Position = TimeSpan.FromSeconds(0);
                    _video.Play();
                }
                
            }
            else
            {
                _video.Source = new Uri(System.AppDomain.CurrentDomain.BaseDirectory + @"Videos\Mainbg.avi", UriKind.Absolute);
                _video.Position = TimeSpan.FromSeconds(0);
                _video.Play();
            }

            }
            catch (Exception)
            {
                
            }
        }

        //按钮声音
        public void PlayerAudio(string _file)
        {
            try
            {
                SoundPlayer player = new SoundPlayer(_file);
                player.Play();
            }
            catch (Exception)
            {
                
            }
            
        }

        //登录窗体启动动画
        public void Loadinglogin(Grid _gd,double _width,double _height)
        {
            DoubleAnimation da = new DoubleAnimation();
            da.From = 0;
            da.To = _width;
            da.Duration = TimeSpan.FromSeconds(0.2);
            DoubleAnimation dah = new DoubleAnimation();
            dah.From = 0;
            dah.To = _height;
            dah.Duration = TimeSpan.FromSeconds(0.5);
            DoubleAnimation dao = new DoubleAnimation();
            dao.From = 0;
            dao.To = 1;
            dao.Duration = TimeSpan.FromSeconds(0.6);


            _gd.BeginAnimation(System.Windows.FrameworkElement.WidthProperty, da);
            _gd.BeginAnimation(System.Windows.FrameworkElement.HeightProperty, dah);
            _gd.BeginAnimation(System.Windows.FrameworkElement.OpacityProperty, dao);
        }

        //主窗体启动动画
        public void LoadingMain(Grid _gd)
        {
            DoubleAnimation dao = new DoubleAnimation();
            dao.From = 0;
            dao.To = 1;
            dao.Duration = TimeSpan.FromSeconds(1);
            _gd.BeginAnimation(System.Windows.FrameworkElement.OpacityProperty, dao);
        }
        #endregion
    }
}
